package com.yc.demo.d0303;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.File;
import java.io.IOException;

@WebServlet(name = "UploadServlet", value = "/UploadServlet")
@MultipartConfig
public class UploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        //从请求中获取文件上传对象Part ,“file” 上传的文件提交的字段名
        Part file = request.getPart("file");
        file.getContentType();//获取文件类型
        file.getName();// ==》z字段名file
        file.getSize();//获取文件大小
        file.getSubmittedFileName();//获取文件名称
        file.write("D:/"+file.getSubmittedFileName());
//        response.getWriter().println("文件上传成功！");
        
        //如何将文件上传webapp下
        //获取赢用上下文对象，上下文 =》运行环境

        ServletContext application = request.getServletContext();
        //将web路径转为磁盘路径
        String realPath = application.getRealPath("/uploads");
        System.out.println("realPath = " + realPath);
        // realPath 的目录不存在，创建文件夹
        new File(realPath).mkdirs();

        file.write(realPath+"/"+file.getSubmittedFileName());
        String webPath = "../uploads/"+ file.getSubmittedFileName();
        response.getWriter().append("文件上传成功");
        if (file.getContentType().contains("image")){
            response.getWriter().printf("<img src = '%s' style='heigh:200px'>",webPath);
        }else{
            response.getWriter().printf("<a href='%s' download ='%s'>%s</a>",webPath,file.getSubmittedFileName(),file.getSubmittedFileName());
        }
    }
}
